package cn.itsource.ymcc.service.impl;

import cn.itsource.ymcc.common.constant.OrderStatus;
import cn.itsource.ymcc.common.constant.RocketConstants;
import cn.itsource.ymcc.domain.PayFlow;
import cn.itsource.ymcc.domain.PayOrder;
import cn.itsource.ymcc.mapper.PayFlowMapper;
import cn.itsource.ymcc.mapper.PayOrderMapper;
import cn.itsource.ymcc.service.IPayOrderService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author zcj
 * @since 2023-12-10
 */
@Service
public class PayOrderServiceImpl extends ServiceImpl<PayOrderMapper, PayOrder> implements IPayOrderService {
    @Autowired
    private PayFlowMapper payFlowMapper;
    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    /**
     *
     * @param parameters
     */
    @Override
    @Transactional
    public void resultHandle(Map<String, String> parameters) {
        //parameters 得到 订单号
        String orderNo = parameters.get("out_trade_no");
        //修改订单的状态   order 服务  //添加购买记录     course 服务
        rocketMQTemplate.syncSend(RocketConstants.UPDATE_ORDER_STATUS_TOPIC+":"+RocketConstants.UPDATE_ORDER_STATUS_TAG,
                orderNo);
        //修改支付单的状态  pay 服务
        PayOrder one = super.getOne(new LambdaQueryWrapper<PayOrder>().eq(PayOrder::getOrderNo, orderNo));
        one.setUpdateTime(new Date());
        one.setPayStatus(OrderStatus.ORDER_PAY);
        super.updateById(one);
        //记录流水        pay服务
        PayFlow payFlow = new PayFlow();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            payFlow.setNotifyTime(sdf.parse(parameters.get("gmt_payment")));
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
        payFlow.setSubject(parameters.get("subject"));
        payFlow.setOutTradeNo(orderNo);
        payFlow.setTotalAmount(new BigDecimal(parameters.get("total_amount")));
        payFlow.setTradeStatus(one.getPayStatus().toString());
        payFlowMapper.insert(payFlow);

        //使用mq通知用户 可以观看了  common服务  只管生产消息
        Map<String,Object> map = new HashMap<>();
        map.put("userId",one.getUserId());
        map.put("content","xxx购买成功可以观看了");
        rocketMQTemplate.sendOneWay(RocketConstants.COURSE_SEND_SMS_TOPIC+":"+RocketConstants.COURSE_SEND_SMS_TAG,
                map);
    }
    //最后还有一个补偿机制 -- 逻辑--定时任务 主动去查询支付单(下单成功待支付) 然后通过订单号去主动查询支付宝  看有没有完成支付  有执行resultHandle逻辑
    //方式二 就是在下单的时候发起一个延迟消息15分分钟  主动去查询支付宝  有有执行resultHandle逻辑 没有取消订单
}
